<!--
 * @Description: 预约限量
 * @Autor: 何兴家
 * @Date: 2020-11-23 13:35:56
 * @LastEditors: 何兴家
 * @LastEditTime: 2021-01-25 14:58:46
-->
<template>
  <div>
    <BreakSpace label="预约时段及间隔时间" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <el-row :gutter="20">
      <el-col :span="15">
        <FormPanel ref="timeTypeForm" :list="timeTypeFormList" :labelWidth="120" :isSubmitBtn="false"></FormPanel>
      </el-col>
      <el-col :span="9">
        <el-button type="primary" @click="handleEditTimeType">编辑</el-button>
        <AjaxButton type="primary" :disabled="savebtnDiabled" :click="handleSaveTimeType">保存</AjaxButton>
      </el-col>
    </el-row>
    <BreakSpace label="预约数量设置" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <el-row :gutter="18">
      <el-col :span="5">
        <FormPanel ref="defaultQuantityForm" :cols="1" :list="defaultQuantityFormList" :labelWidth="120" :isSubmitBtn="false"></FormPanel>
      </el-col>
      <el-col :span="9">
        <el-button type="primary" @click="handleApplyClick">应用</el-button>
        <AjaxButton type="primary" :click="handleExportTemplate">导出模板</AjaxButton>
        <UploadFile
          style="margin: 0 10px;"
          :initial-value="fileInitalValue"
          isOnlyButton
          :disabled="importBtnDisabled"
          :actionUrl="`${server.DMSCLOUD_REPAIR}/precontractStatus//importPrecontractLimit`"
          @change="handleUploadChange"
          >导入数据</UploadFile
        >
      </el-col>
    </el-row>
    <FilterTable
      ref="table"
      columnsRef="repair_repairBusiness_appointmentLimit"
      height="auto"
      :isSelectColumn="false"
      :isToperInfo="false"
      :isPagination="false"
      :isColumnFilter="false"
      :dataSource="tableDataSource"
      :columns="tableColumns"
      :onColumnsChange="columns => (this.tableColumns = columns)"
      :onSyncTableData="handleTableDataChange"
    >
    </FilterTable>
    <div class="bottomBtnWrap">
      <AjaxButton type="primary" :click="handleSaveBtnClick">保存</AjaxButton>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
import { confirmAction, notifyAction, exportExcelFile } from '@/utils';
import server from '@/api/server';

import { updateTimeInterval, saveBookingLimitList, exportTemplate, queryBookingLimitList } from '@/api/repair/repairBusiness/appointmentLimit';
import { findAllRepair } from '@/api/repair/common';

export default {
  data() {
    return {
      timeTypeFormList: this.createTimeTypeFormList(),
      defaultQuantityFormList: this.createDefaultQuantityFormList(),
      tableColumns: this.createTableColumns(),
      server,
      fileInitalValue: [],
      savebtnDiabled: true, // 上方保存按钮是否禁用
      importBtnDisabled: false, // 导入按钮是否禁用
      tableDataSource: [], // table初始化数据
      syncTableData: [] // 同步的table数据
    };
  },
  mounted() {
    this.queryDefaultTimeType();
    this.initTimeItemList();
    this.queryTableData();
  },
  methods: {
    createTimeTypeFormList() {
      return [
        {
          type: 'SELECT',
          label: '可预约开始时间',
          fieldName: '1020',
          itemList: [],
          disabled: true,
          initialValue: '',
          rules: [{ required: true, message: '请选择可预约开始时间', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '可预约结束时间',
          fieldName: '1021',
          itemList: [],
          disabled: true,
          initialValue: '',
          rules: [{ required: true, message: '请选择可预约结束时间', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '预约时间短间隔',
          fieldName: '1022',
          itemList: [
            { text: 10, value: 10 },
            { text: 15, value: 15 },
            { text: 20, value: 20 },
            { text: 30, value: 30 },
            { text: 60, value: 60 }
          ],
          disabled: true,
          initialValue: '',
          rules: [{ required: true, message: '请选择预约时间短间隔', trigger: 'change' }]
        }
      ];
    },
    createDefaultQuantityFormList() {
      return [
        {
          type: 'INPUT_NUMBER',
          label: '默认预约限量',
          fieldName: '1024',
          itemList: [],
          initialValue: ''
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '小时',
          dataIndex: 'hour'
        },
        {
          title: '周一',
          dataIndex: 'monday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '周二',
          dataIndex: 'tuesday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '周三',
          dataIndex: 'wednesday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '周四',
          dataIndex: 'thursday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '周五',
          dataIndex: 'friday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '周六',
          dataIndex: 'saturday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '周日',
          dataIndex: 'sunday',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        }
      ];
    },
    // 查询默认参数
    async queryDefaultTimeType() {
      let res = await findAllRepair();
      if (res.resultCode == 200) {
        this.timeTypeFormList.forEach(item => {
          item.initialValue = res.data[item.fieldName] ? +res.data[item.fieldName] : '';
        });
        this.defaultQuantityFormList.find(item => item.fieldName === '1024').initialValue = res.data[1024];
      }
    },
    // 初始化时间下拉框选项
    initTimeItemList() {
      this.timeTypeFormList.find(item => item.fieldName === '1020').itemList = this.createDayTimeList(0, 24);
      this.timeTypeFormList.find(item => item.fieldName === '1021').itemList = this.createDayTimeList(0, 24);
    },
    // 创建时间字典项
    createDayTimeList(start, end) {
      let arr = [];
      for (let i = start; i < end; i++) {
        arr.push({
          text: i + ':00',
          value: i
        });
      }
      return arr;
    },
    // 查询预约限量数据
    async queryTableData() {
      this.$refs.table.START_LOADING();
      try {
        let res = await queryBookingLimitList();
        if (res.resultCode == 200) {
          res.data.forEach(item => (item.hour = item.TIME));
          this.tableDataSource = res.data;
        }
      } catch (err) {
        console.log(err, '查询主列表失败');
      } finally {
        this.$refs.table.STOP_LOADING();
      }
    },
    // 时间类型编辑
    handleEditTimeType() {
      this.timeTypeFormList.forEach(item => {
        item.disabled = false;
      });
      this.savebtnDiabled = false;
    },
    // 时间类型保存
    async handleSaveTimeType() {
      let formData = await this.$refs.timeTypeForm.GET_FORM_DATA();
      if (formData[0]) return false;
      if (formData[1][1020] >= formData[1][1021]) {
        notifyAction('可预约开始时间不能小于可预约结束时间，请调整', 'warning');
        return false;
      }
      try {
        let confirmType = await confirmAction('调整时间段或者间隔时间后需要重新设置预约限量，是否继续？');
        if (confirmType) {
          try {
            let res = await updateTimeInterval({
              beginTime: formData[1][1020],
              endTime: formData[1][1021],
              timeInterval: formData[1][1022]
            });
            if (res.resultCode == 200) {
              this.timeTypeFormList.forEach(item => {
                item.disabled = true;
              });
              this.savebtnDiabled = true;
              notifyAction('预约时间段及时间间隔保存成功', 'success');
              let newTableData = this.createTableDataBasicData(formData[1][1020], formData[1][1021], formData[1][1022]);
              this.tableDataSource = newTableData;
              newTableData.forEach(item => {
                item.bookingHour = item.hour.split('-')[0];
                item.bookingMinute = item.hour.split('-')[1];
              });
              await this.submitFun(newTableData);
            }
          } catch (err) {
            console.log(err, '保存失败');
            return false;
          }
        }
      } catch (err) {}
    },
    // 点击应用按钮
    handleApplyClick() {
      let defaultQuantity = this.defaultQuantityFormList.find(item => item.fieldName === '1024').initialValue;
      if (_.isNil(defaultQuantity)) return notifyAction('请先维护默认预约数量');
      this.syncTableData.forEach(item => {
        item.monday = item.tuesday = item.wednesday = item.thursday = item.friday = item.saturday = item.sunday = defaultQuantity;
      });
    },
    // 点击导出模板
    async handleExportTemplate() {
      let res = await exportTemplate();
      res.data.size != 0 && exportExcelFile(res.data, '预约限量导入模板');
    },
    // 导入成功回调
    handleUploadChange(e) {
      this.$nextTick(() => {
        if (e[0] && e[0].status === 'success') {
          notifyAction('导入成功', 'success');
          e[0].url.forEach(item => {
            item.hour = item.bookingHour;
          });
          this.tableDataSource = e[0].url;
          this.fileInitalValue = [];
        }
      });
    },
    // 同步表格数据
    handleTableDataChange(list) {
      this.syncTableData = list;
    },
    // 根据时间段及间隔创建table列表数据
    createTableDataBasicData(start, end, interval) {
      let step = 60 / interval,
        arr = [];
      for (let i = start; i < end; i++) {
        for (let j = 0; j < step; j++) {
          arr.push({
            hour: i + ':' + (interval * j || '00') + '-' + (j == step - 1 ? i + 1 + ':00' : i + ':' + interval * (j + 1)),
            monday: 0,
            tuesday: 0,
            wednesday: 0,
            thursday: 0,
            friday: 0,
            saturday: 0,
            sunday: 0
          });
        }
      }
      return arr;
    },
    // 点击保存按钮
    async handleSaveBtnClick() {
      let dataClone = _.cloneDeep(this.syncTableData);
      dataClone.forEach(item => {
        item.bookingHour = item.hour.split('-')[0];
        item.bookingMinute = item.hour.split('-')[1];
      });
      await this.submitFun(dataClone);
    },
    // 保存提交函数
    async submitFun(data) {
      this.$refs.table.START_LOADING();
      try {
        let res = await saveBookingLimitList(data);
        if (res.resultCode == 200) {
          notifyAction('预约限量保存成功', 'success');
        }
      } catch (err) {
        console.log(err, '保存失败');
      } finally {
        this.$refs.table.STOP_LOADING();
      }
    }
  }
};
</script>

<style scoped>
.bottomBtnWrap {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
